package com.yt.demo.config;

import com.yt.demo.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * /当前类是一个Spring的配置类，用于模拟Spring的配置文件
 *
 * @Configuration： 表示当前类作为配置文件使用（配置容器，放在类的上面；等同 xml 配置文件，可以在其中声明 bean ）
 * @Bean： 将对象注入到Spring容器中（类似<bean>标签，放在方法上面）；不指定对象的名称，默认是方法名是 id
 */

@Configuration
public class ShiroConfig {

    //    @Autowired
//    private MyRealm myRealm;
    @Bean
    public Realm realm() {
        MyRealm myRealm = new MyRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(3);

        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        System.out.println("======自定义realm完成========");
        return myRealm;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(realm());
        defaultWebSecurityManager.setRememberMeManager(rememberMeManager());
//        ThreadContext.bind(defaultWebSecurityManager);
        return defaultWebSecurityManager;
    }

    private SimpleCookie rememberMeCookie() {
        System.out.println("======rememberMe to cookie========");
        SimpleCookie sc=new SimpleCookie("rememberMe");
        sc.setPath("/");
        sc.setHttpOnly(true);
        sc.setMaxAge(30*24*60*60);
        return sc;
    }
    private CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager=new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        //此处一坑，必须16位
        cookieRememberMeManager.setCipherKey("yangtaoyangtaoyy".getBytes());
        return cookieRememberMeManager;
    }
//    @Bean
//    public ShiroFilterFactoryBean shirFilter(DefaultWebSecurityManager securityManager) {
//
//        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
//        // 必须设置 SecurityManager
//        shiroFilter.setSecurityManager(securityManager);
//        // 拦截器
//        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
//        // 设置login URL
//        shiroFilter.setLoginUrl("/shiro/login");
//        // 登录成功后要跳转的链接
////        shiroFilter.setSuccessUrl("/index");
//        filterChainDefinitionMap.put("/webjars/**", "anon");
//        filterChainDefinitionMap.put("/druid/**", "anon");
//        //静态资源的处理
//        filterChainDefinitionMap.put("/js/**", "anon");
//        filterChainDefinitionMap.put("/css/**", "anon");
//        filterChainDefinitionMap.put("/asserts/**", "anon");
//        filterChainDefinitionMap.put("/fonts/**", "anon");
//        filterChainDefinitionMap.put("/images/**", "anon");
//        //解决小问题/favicon.ico
//        filterChainDefinitionMap.put("/favicon.ico", "anon");
//
//        // 退出系统的过滤器
//        //发现有登出过滤，于是删除了controller里的方法
//        filterChainDefinitionMap.put("/logout", "logout");
//        filterChainDefinitionMap.put("/login", "anon");
//
//        filterChainDefinitionMap.put("/kaptcha", "anon");
//
////        filterChainDefinitionMap.put("/**", "authc");
//        filterChainDefinitionMap.put("/success", "user");
//        filterChainDefinitionMap.put("/**", "authc");
//        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
//        return shiroFilter;
//    }

    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/shiro/login", "anon");//不需要认证的路径
        definition.addPathDefinition("/login", "anon");//不需要认证的路径
        definition.addPathDefinition("/success", "user");//需要用户的路径
        definition.addPathDefinition("/logout", "logout");//需要用户的路径
        definition.addPathDefinition("/**", "authc");//需要认证的路径
        return definition;
    }



    //注解无效解决方案：
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor=new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


}